package com.oplink.webems.modules.cfg.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.common.snmp.base.SnmpException;
import com.oplink.webems.common.snmp.entity.Card;
import com.oplink.webems.common.snmp.service.NodePoll;
import com.oplink.webems.common.snmp.service.SnmpService;
import com.oplink.webems.modules.cfg.entity.CfgNe;
import com.oplink.webems.modules.cfg.entity.CfgSite;
import com.oplink.webems.modules.cfg.entity.CfgSlot;
import com.oplink.webems.modules.cfg.services.CfgNeService;
import com.oplink.webems.modules.cfg.services.CfgSiteService;
import com.oplink.webems.modules.cfg.services.CfgSlotService;
import com.oplink.webems.modules.event.service.EventCenter;
import com.oplink.webems.modules.sys.dto.MsgDTO;
import com.oplink.webems.modules.sys.dto.RespDTO;
import com.oplink.webems.modules.sys.service.ConfigService;

/**
 * Title: 网元配置控制器
 * Description:
 * Copyright: Copyright (c) 2014
 * Company: Oplink Communications
 * 
 * @author
 * @serialData 2014-9-17 上午11:33:18
 * @version 1.0
 */
@Controller
@RequestMapping(value = "cfg/ne")
public class CfgNeController {

	@Autowired
	private ConfigService cfgService;

	@Autowired
	private CfgNeService neService;

	@Autowired
	private CfgSiteService siteService;

	@Autowired
	private CfgSlotService slotService;

	@Autowired
	private SnmpService snmpService;

	@Autowired
	private EventCenter ec;

	@RequestMapping(value = "")
	public String neCfg(CfgNe ne, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<CfgNe> page = neService.find(new Page<CfgNe>(request, response), ne);
		model.addAttribute("pages", page);
		model.addAttribute("entity", ne);
		return "modules/cfg/neIndex";
	}

	/**
	 * 心跳检测
	 * 
	 * @return
	 */
	@RequestMapping(value = "ping", method = RequestMethod.GET)
	@ResponseBody
	public String ping() {
		return "0";
	}

	@RequestMapping(value = "listCard/{neId}")
	@ResponseBody
	public List<CfgSlot> ListCard(@PathVariable("neId") Long neId) {
		return neService.getSlotByNid(neId);
	}

	/**
	 * 主要用于显示
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public CfgNe updateForm(@PathVariable("id") Long id) {
		CfgNe ne = neService.getCfgNe(id);
		return ne;
	}

	/**
	 * 获取指定网元下的槽位
	 * 
	 * @param nid
	 * @return
	 */
	@RequestMapping(value = "slots/{nid}", method = RequestMethod.GET)
	@ResponseBody
	public List<CfgSlot> getSlots(@PathVariable("nid") Long id) {
		CfgNe ne = neService.getCfgNe(id);
		if (ne != null) {
			return ne.getSlotlist();
		}
		return null;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public RespDTO update(@Valid @ModelAttribute("entity") CfgNe entity, RedirectAttributes redirectAttributes) {
		RespDTO res = new RespDTO(RespDTO.ERROR, "");
		try {
			CfgSite site = entity.getSite();
			if (site.getSid() != null) {
				if (neService.getByIP(entity.getIp()).size() < 2) {
					long ret = neService.save(entity).longValue();

					CfgSite uSite = siteService.getEntity(site.getSid());
					uSite.setEnable(site.getEnable());
					uSite.setLabel(site.getLabel());
					uSite.setValue(site.getValue());
					entity.setSite(uSite);

					res.setResult(RespDTO.SUCCESS);
					res.setMessage(ret + "");
					neService.save(entity);
				} else {
					res.setMessage(MsgDTO.ERR_EXIST_IP_ADDR);
				}

			}
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return res;
		} catch (Exception e) {
			res.setMessage(e.getMessage());
			return res;
		}
	}

	/**
	 * 根据网元ID查询其上面板卡状态
	 * 
	 * @param nid
	 * @return
	 */
	@RequestMapping(value = "queryNeCards/{nid}", method = RequestMethod.GET)
	@ResponseBody
	public List<Card> queryNeCards(@PathVariable("nid") Long nid) {
		CfgNe ne = neService.getCfgNe(nid);
		String ip = ne.getIp();
		if (ip != null) {
			snmpService.connectV2(ip, "Admin@123");
			try {
				return snmpService.scanCards();
			} catch (SnmpException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public RespDTO create(@Valid @ModelAttribute("entity") CfgNe entity, RedirectAttributes redirectAttributes,
			Model model) {
		RespDTO res = new RespDTO(RespDTO.ERROR, "");
		String name = entity.getNename();
		if (neService.getByName(name) == null) {
			model.addAttribute("entity", entity);
			// 检验IP是否存在
			if (neService.getByIP(entity.getIp()).size() < 2) {
				long ret = neService.save(entity).longValue();
				res.setResult(RespDTO.SUCCESS);
				res.setMessage(ret + "");

				ec.putNe(entity, true);
				NodePoll.hasNewNode = true;
			} else {
				res.setMessage(MsgDTO.ERR_EXIST_IP_ADDR);
			}
		} else {
			// 名字已经存在
			res.setMessage(MsgDTO.ERR_EXIST_NE_NAME);
		}
		return res;
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public RespDTO delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		RespDTO ret = new RespDTO(RespDTO.ERROR, "");
		if (!"".equals(id)) {
			String[] delList = id.split(",");
			for (String idItem : delList) {
				CfgNe entity = neService.getOneCfgNe(Long.valueOf(idItem));
				if (entity.getNid() != null) {
					ec.putNe(entity, false);
					neService.delete(entity.getNid());
				}
			}
			ret.setResult(RespDTO.SUCCESS);
		} else {
			ret.setMessage(MsgDTO.ERR_NOT_FOUND_NE);
		}
		return ret;
	}

	@ResponseBody
	@RequestMapping(value = "getcard")
	public String getcard(String ne, String slot) {
		long cardid = slotService.getcard(Long.parseLong(ne), Long.parseLong(slot));
		String neJson = JSONObject.toJSONString(cardid);
		return neJson;
	}

}
